#include "state_diagram.h"
#include "krryn.h"
#include "string_util.h"
#include "widget_factory.h"
#include "diagram.h"
#include "render_control.h"
#include "animation_diagram.h"
#include <fstream>

using namespace krryn::math;
using namespace krryn::system;
using namespace krryn::usr;
using namespace krryn::core;
using namespace krryn::view;
using namespace krryn::gui;

/////////////////////////
namespace{
	window *m_Window;
	diagram *m_Diagram;
	render_control *m_RenderControl;
	renderer *m_Renderer;
}

static state_diagram _state_diagram;

state_diagram::~state_diagram(){}

void state_diagram::init(){
	m_Window = window::with()
		.width(640 + 320)
		//.left(0)
		.height(480)
	.create();

	m_Diagram = diagram::with()
		.width(640)
		.height(480)
		.parent(m_Window)
		.factory(new diagram_factory_default())
	.create();

	try{
		if(arguments::has("nodes")){
			m_Diagram->load(arguments::get("nodes"));
		}
	}catch(std::runtime_error &){
		m_Diagram->create_node("Animation: Idle");
		m_Diagram->create_node("Animation: Run", 667)->move_to(100, 100);
		m_Diagram->create_node("blend", 668)->move_to(-100, 100);
		m_Diagram->create_node("output", 669)->move_to(-100, 200);
	}

	m_RenderControl = render_control::with()
		.top(0)
		.left(640)
		.width(320)
		.height(240)
		.parent(m_Window)
		.api("opengl")
		.vsync(false)
	.create();

	m_Renderer = m_RenderControl->get_renderer();
}

void state_diagram::activate(){}

void state_diagram::deactivate(){}

void state_diagram::tick(float a_DeltaTime){
	m_RenderControl->swap_buffers();
	m_EventLoop.update();

	if(arguments::has("nodes")) m_Diagram->save(arguments::get("nodes"));
}